<template>
	<view>

	</view>
</template>

<script>
import {
		WechatUserInfo
	} from '@/api/login.js'
	import {
		HTTP_REQUEST_URL,
		AppID,
		LOGIN_URL
	} from '@/config/app';
	export default {
		data() {
			return {
				authCode:null
			}
		},
		onLoad(options) {
			
		},
		onShow() {
			this.appInit()
		},
		methods: {
			async appInit() {
				uni.showLoading({
					title: '加载中...'
				})
				const url = LOGIN_URL; 
				const appid = AppID;
				const redirect_uri = encodeURIComponent(LOGIN_URL);
				const code = this.getUrlCode().code;
				console.log(code, !code, "code,")
				if (!code) {
					const href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
					/* const href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
						appid +
						"&redirect_uri=" + encodeURIComponent(url) +
						"&response_type=code&scope=snsapi_userinfo#wechat_redirect"; */
					console.log(href,'href');
					//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx29eb7d1d2efaec00&redirect_uri=http%3A%2F%2F172.16.25.194%3A8080&response_type=code&scope=snsapi_userinfo#wechat_redirect
					
					window.location.href = href;
				} else {
					const params = {
						code: code
					};
					const userInfo = await WechatUserInfo(params);
					const openid = userInfo.retData.openId;
					const token = userInfo.retData.token;
					uni.setStorageSync('openid', openid);
					if(token){
						uni.setStorageSync('userToken',token);
						console.log(uni.getStorageSync('userToken'),'uni.getStorageSyncToken');
						uni.navigateTo({
							url:'/pages/index/index'
						})
					}
					
					uni.hideLoading()
				}
			},
			getUrlCode() {
				// 截取url中的code方法
				var url = location.search;
				var theRequest = new Object();
				if (url.indexOf("?") != -1) {
					var str = url.substr(1);
					var strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
					}
				}
				console.log(theRequest);
				return theRequest;
			},
		}
	}
</script>

<style>

</style>